package student.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import student.aistar.model.bo.Result;
import student.aistar.model.entity.*;
import student.aistar.service.IIndexService;
import student.aistar.service.IPersonalCenterService;
import student.aistar.service.IProductService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/personal_center")
public class PersonalCenterController {

    @Autowired
    private IPersonalCenterService iPersonalService;

    @Autowired
    private IProductService iProductService;
    @Autowired
    private IIndexService iIndexService;


    @GetMapping("/portal")
    public String Portal(HttpSession session,Model model){
        List<Navclass> navClassList = iIndexService.navClassList();
        model.addAttribute("navClassList", navClassList);
        User user = (User) session.getAttribute("user");
        int ordersss = iPersonalService.selectOrdersStatusByUserId(user.getUserId());
        int orderssss = iPersonalService.selectOrdersStatusByUserId2(user.getUserId());
        int likes = iPersonalService.selectCountLike(user.getUserId());
        User userOne = iPersonalService.selectById(user.getUserId());
        String b = user.getUserTelephone().substring(7);
        String a = user.getUserTelephone().substring(0,3);
        userOne.setUserTelephone(a + "****" + b);
        if( user.getUserEmail() != null) {
            String c = user.getUserEmail().substring(0, 2);
            userOne.setUserEmail(c + "******@qq.com");
        }

        model.addAttribute("likes",likes);
        model.addAttribute("ordersss",ordersss);
        model.addAttribute("orderssss",orderssss);
        model.addAttribute("user",userOne);
        return "mi/personal_center/portal";
    }

    @GetMapping("/likes")
    public String Likes(Model model, HttpSession httpSession){
        List<Navclass> navClassList = iIndexService.navClassList();
        model.addAttribute("navClassList", navClassList);
        //将查询到的我的喜欢的数据和商品数据返回到页面
        User user = (User) httpSession.getAttribute("user");

        List<Collect> collects = iPersonalService.userLike(user.getUserId());//根据userid获取到喜欢的商品的集合
        List<Product> products = new ArrayList<>();
        for (int i = 0; i < collects.size(); i++) {
            Product product = iProductService.findById(collects.get(i).getProductId());
            products.add(product);
        }

        model.addAttribute("collects",collects);

        model.addAttribute("products",products);

        return "mi/personal_center/likes";
    }


    // 根据产品id删除我的喜欢的商品
    @GetMapping("/deleteMyLike")
    public String deleteMyLike(Integer productId, HttpSession session){
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserId();
        iPersonalService.deleteUserLike(productId, userId);
        return "redirect:likes";
    }

    @GetMapping("/personal_info")
    public String personalInfo(HttpSession session,Model model){
        User user = (User) session.getAttribute("user");
        User userOne = iPersonalService.selectById(user.getUserId());
        String b = user.getUserTelephone().substring(7);
        String a = user.getUserTelephone().substring(0,3);
        userOne.setUserTelephone(a+"****"+b);

        model.addAttribute("user",userOne);
        return "mi/personal_center/personal_info";
    }

    @PostMapping("/personal_info2")
    @ResponseBody
    public Result personalInfo2(User user, Model model){
//        System.out.println(user);
//        System.out.println(user);
        User userDataBase = iPersonalService.selectByName(user.getUserName());
        if (user.getUserName().equals("")){
            return new Result("404","修改失败,昵称不能为空!");
        }

        iPersonalService.updateUserInfo(user.getUserId(),user.getUserName(),user.getSex(),user.getUserImg());
//        System.out.println(iPersonalService.selectById(user.getUserId()).getUserImg());

        model.addAttribute("imgSrc", iPersonalService.selectById(user.getUserId()).getUserImg());
        return new Result("200","修改成功", iPersonalService.selectById(user.getUserId()).getUserImg());
    }

    @GetMapping("/personal_login")
    public String personalLogin(Model model,HttpSession session){
        User user = (User) session.getAttribute("user");
        User userOne = iPersonalService.selectById(user.getUserId());
        System.out.println(userOne);

        model.addAttribute("userTest", userOne);
        String b = user.getUserTelephone().substring(7);
        String a = user.getUserTelephone().substring(0,3);
        String c = user.getUserEmail().substring(0,2);
        userOne.setUserTelephone(a+"****"+b);
        userOne.setUserEmail(c+"******@qq.com");

        model.addAttribute("newUser", userOne);

        model.addAttribute("userOne",userOne);
        return "mi/personal_center/personal_login";
    }

    @PostMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile file, HttpServletRequest request){
        //获取属性
        String filename = file.getOriginalFilename();
        //重新生成一个新的名称
        String newFileName = UUID.randomUUID().toString()+"_"+filename;

        //获取imgs的绝对路径
        ///Users/admin/Documents/success/teaching/wksp/spring-j13/springboot-j03s/src/main/webapp/
        String path = request.getServletContext().getRealPath("/");

        //写出去
        File f = new File(path+"imgs/"+newFileName);
        try {
            file.transferTo(f);
        } catch (IOException e) {

            e.printStackTrace();
            return new Result("500","文件上传失败");
        }

        return new Result("200","文件上传成功",newFileName);
    }


    @PostMapping("/jiaoyan")
    @ResponseBody
    public Result jiaoyan(String userTelephone){
        //手机号正则表达式
        Pattern phoneReg = Pattern.compile("^((13[0-9])|(14[0|5|6|7|9])|(15[0-3])|(15[5-9])|(16[6|7])|(17[2|3|5|6|7|8])|(18[0-9])|(19[1|8|9]))\\d{8}$");
        Matcher m = phoneReg.matcher(userTelephone);
        if(!m.matches())
            return new Result("500", "手机号码输入格式有误");
        return new Result("200","修改成功!");
    }

    @GetMapping("/personal_login2")
    public String personalLogin2(Model model, Integer userId,String userTelephone) {


        iPersonalService.updateTelephoneByUserId(userId,userTelephone);

        User userOne = iPersonalService.selectById(userId);
        System.out.println(userOne);

        model.addAttribute("userTest", userOne);
        String b = userOne.getUserTelephone().substring(7);
        String a = userOne.getUserTelephone().substring(0,3);
        String c = userOne.getUserEmail().substring(0,2);
        userOne.setUserTelephone(a+"****"+b);
        userOne.setUserEmail(c+"******@qq.com");

        model.addAttribute("newUser", userOne);

        model.addAttribute("userOne",userOne);
        return "mi/personal_center/personal_login";
    }

    @GetMapping("/personal_login3")
    public String personalLogin3(Model model,Integer userId,String userEmail) {
        iPersonalService.updateEmailByUserId(userId,userEmail);
        User userOne = iPersonalService.selectById(userId);
        System.out.println(userOne);

        model.addAttribute("userTest", userOne);
        String b = userOne.getUserTelephone().substring(7);
        String a = userOne.getUserTelephone().substring(0,3);
        String c = userOne.getUserEmail().substring(0,2);
        userOne.setUserTelephone(a+"****"+b);
        userOne.setUserEmail(c+"******@qq.com");

        model.addAttribute("newUser", userOne);

        model.addAttribute("userOne",userOne);
        return "mi/personal_center/personal_login";
    }

    @GetMapping("/personal_login4")
    public String personalLogin4(Integer userId,String userPassword) {
        iPersonalService.updatePasswordByUserId(userId,userPassword);
        return "redirect:personal_login";
    }


    @PostMapping("/delete_like")
    @ResponseBody
    public Result deleteLike(HttpSession session,Integer productId){
        User user = (User) session.getAttribute("user");
        iPersonalService.deleteUserLike(productId,user.getUserId());

        return new Result("200", "删除成功");
    }


    @PostMapping("/dealCollect")
    @ResponseBody
    public Result dealCollect(HttpSession session,Integer productId, Integer status){
        User user = (User) session.getAttribute("user");
        Collect collect = iPersonalService.selectCollectionByUserIdAndProductId(user.getUserId(), productId);
        if(collect == null && status == 0){
            Product collectProduct = iProductService.findById(productId);
            iPersonalService.insertProductToLike(new Collect(null, user.getUserId(), productId, collectProduct.getProductName(), collectProduct.getPicImg(), collectProduct.getPrice(), collectProduct.getProductName()));
            return new Result("200", "收藏成功");
        }
        else if(collect != null && status == 1) {
            iPersonalService.deleteUserLike(productId,user.getUserId());
            return new Result("300", "取消收藏");
        }
        return new Result();
    }
}

